package controllers

import (
	"cdam/models"
	"cdam/stock"
	"cdam/util"
	"encoding/json"
	"errors"
	"math/rand"
	"strconv"
	"strings"
	"time"

	"github.com/astaxie/beego"
)

// DetailController operations for DetailModel
type DetailController struct {
	beego.Controller
}

// URLMapping ...
func (c *DetailController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetOne", c.GetOne)
	c.Mapping("GetAll", c.GetAll)
	c.Mapping("Put", c.Put)
	c.Mapping("Delete", c.Delete)
	c.Mapping("GetCondition", c.GetCondition)
	c.Mapping("GetDataFromNetHistory",c.GetDataFromNetHistory)
}

// Post ...
// @Title Post
// @Description create Detail
// @Param	body		body 	models.Detail	true		"body for Detail content"
// @Success 201 {int} models.Detail
// @Failure 403 body is empty
// @router / [post]
func (c *DetailController) Post() {
	var v models.Detail
	m := map[string]interface{}{}
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &v); err == nil {
		v.Id = int64(rand.New(util.Seed).Int63n(100000000))
		// v.Createdate = time.Now()
		if _, err := models.AddDetail(&v); err == nil {
			c.Ctx.Output.SetStatus(201)
			m["code"] = "20000"
		} else {
			m["code"] = "80000"
			m["message"] = err.Error()
		}
	} else {
		m["code"] = "80000"
		m["message"] = err.Error()
	}
	c.Data["json"] = m
	c.ServeJSON()
}

// GetDataFromNet ...
// @Title 根据条件获取结果
// @Description 根据条件获取结果
// @Param	code		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.Detail
// @Failure 403
// @router /GetDataFromNetHistory/:code [get]
func (c *DetailController)GetDataFromNetHistory()  {
	m := map[string]interface{}{}
	code := c.Ctx.Input.Param(":code")
	//firstDay := time.Now().AddDate(0, 0, -time.Now().Day() + 1)
	path := "./files/shanghai/" + code
	err := util.PathIsNotExistAndCreate(path)
	if err != nil {
		m["message"] = err
		m["code"] = "80000"
	}else{
		stockUtil := stock.StockInit()
		// 上个月第一天
		// begin := firstDay.AddDate(0,-1,0)
		begin := time.Now().AddDate(0, 0, -4)
		for ; !util.IsSameDay(begin,time.Now()); begin = begin.AddDate(0,0,1) {
			format := "20060102"
			d := begin.Format(format)
			fileName := path + "/" + d + ".cvs"
			// http://stock.gtimg.cn/data/index.php?appn=detail&action=download&c=sh600103&d=20200701
			durl := "http://stock.gtimg.cn/data/index.php?appn=detail&action=download&c=" + code + "&d=" + d
			if err := stockUtil.DownloadExcel(fileName,durl); err != nil {
				m["messsage"] = err
				m["code"]="80000"
			}else{
				if result,err := stockUtil.ReadExcel(fileName,d); err != nil {
					m["messsage"] = err
					m["code"]="80000"
				}else{
					for index,value := range result {
						if index >= 2 {
							detail := models.Detail{}
							detail.Id = int64(rand.New(util.Seed).Int63n(100000000))
							detail.Code = code
							detail.Begindate = d
							detail.Starttime = value[0]
							detail.Price,_ = strconv.ParseFloat(value[1],64)
							detail.Change , _ = strconv.ParseFloat(value[2],64)
							detail.Count,_ = strconv.ParseInt(value[3],0,64)
							detail.Total,_ = strconv.ParseFloat(value[4],64)
							//detail.Type = value[5]
							_ ,err := models.AddDetail(&detail)
							if err != nil {
								m["messsage"] = err
								m["code"]="80000"
							}
						}
					}
					//os.Remove(fileName)
				}
			}
		}
		m["code"] ="20000"
	}
	c.Data["json"] = m
	c.ServeJSON()
}

// GetAllByCondition ...
// @Title 根据条件获取结果
// @Description 根据条件获取结果
// @Param	query	query	string	false	"Filter. e.g. col1:v1,col2:v2 ..."
// @Success 200 {object} models.Detail
// @Failure 403
// @router /GetCondition [get]
func (c *DetailController) GetCondition() {
	m := map[string]interface{}{}
	var query = make(map[string]string)
    // query: k:v,k:v
	if v := c.GetString("query"); v != "" {
		for _, cond := range strings.Split(v, ",") {
			kv := strings.SplitN(cond, ":", 2)
			if len(kv) != 2 {
				c.Data["json"] = errors.New("Error: invalid query key/value pair")
				c.ServeJSON()
				return
			}
			k, v := kv[0], kv[1]
			query[k] = v
		}
	}
	l, err := models.GetDetailByCondition(query)
	if err != nil {
		m["code"] = "80000"
		m["message"] = err.Error()
	} else {
		m["code"] = "20000"
		m["data"] = l
	}
	c.Data["json"] = m
	c.ServeJSON()
}

// GetOne ...
// @Title Get One
// @Description get Detail by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.Detail
// @Failure 403 :id is empty
// @router /:id [get]
func (c *DetailController) GetOne() {
	idStr := c.Ctx.Input.Param(":id")
	id, _ := strconv.Atoi(idStr)
	v, err := models.GetDetailById(int64(id))
	var m = make(map[string]interface{})
	if err != nil {
		m["code"] = "80000"
		m["message"] = err.Error()
	} else {
		m["code"] = "20000"
		m["detail"] = v
	}
	c.Data["json"] = m
	c.ServeJSON()
}

// GetAll ...
// @Title Get All
// @Description get Detail
// @Param	query	query	string	false	"Filter. e.g. col1:v1,col2:v2 ..."
// @Param	fields	query	string	false	"Fields returned. e.g. col1,col2 ..."
// @Param	sortby	query	string	false	"Sorted-by fields. e.g. col1,col2 ..."
// @Param	order	query	string	false	"Order corresponding to each sortby field, if single value, apply to all sortby fields. e.g. desc,asc ..."
// @Param	limit	query	string	false	"Limit the size of result set. Must be an integer"
// @Param	offset	query	string	false	"Start position of result set. Must be an integer"
// @Success 200 {object} models.Detail
// @Failure 403
// @router / [get]
func (c *DetailController) GetAll() {
	var fields []string
	var sortby []string
	var order []string
	var query = make(map[string]string)
	var limit int64 = 10
	var offset int64

	// fields: col1,col2,entity.col3
	if v := c.GetString("fields"); v != "" {
		fields = strings.Split(v, ",")
	}
	// limit: 10 (default is 10)
	if v, err := c.GetInt64("limit"); err == nil {
		limit = v
	}
	// offset: 0 (default is 0)
	if v, err := c.GetInt64("offset"); err == nil {
		offset = v
	}
	// sortby: col1,col2
	if v := c.GetString("sortby"); v != "" {
		sortby = strings.Split(v, ",")
	}
	// order: desc,asc
	if v := c.GetString("order"); v != "" {
		order = strings.Split(v, ",")
	}
	// query: k:v,k:v
	if v := c.GetString("query"); v != "" {
		for _, cond := range strings.Split(v, ",") {
			kv := strings.SplitN(cond, ":", 2)
			if len(kv) != 2 {
				c.Data["json"] = errors.New("Error: invalid query key/value pair")
				c.ServeJSON()
				return
			}
			k, v := kv[0], kv[1]
			query[k] = v
		}
	}

	l, count, err := models.GetAllDetail(query, fields, sortby, order, offset, limit)
	m := map[string]interface{}{}
	if err != nil {
		m["code"] = "80000"
		m["message"] = err.Error()
	} else {
		m["code"] = "20000"
		m["data"] = l
		m["count"] = count
	}
	c.Data["json"] = m
	c.ServeJSON()
}

// Put ...
// @Title Put
// @Description update the Detail
// @Param	id		path 	string	true		"The id you want to update"
// @Param	body		body 	models.Detail	true		"body for Detail content"
// @Success 200 {object} models.Detail
// @Failure 403 :id is not int
// @router /:id [put]
func (c *DetailController) Put() {
	idStr := c.Ctx.Input.Param(":id")
	id, _ := strconv.Atoi(idStr)
	v := models.Detail{Id: int64(id)}
	m := map[string]interface{}{}
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &v); err == nil {
		if err := models.UpdateDetailById(&v); err == nil {
			m["code"] = "20000"
		} else {
			m["code"] = "80000"
			m["message"] = err.Error()
		}
	} else {
		m["code"] = "80000"
		m["message"] = err.Error()
	}
	c.Data["json"] = m
	c.ServeJSON()
}

// Delete ...
// @Title Delete
// @Description delete the Detail
// @Param	id		path 	string	true		"The id you want to delete"
// @Success 200 {string} delete success!
// @Failure 403 id is empty
// @router /:id [delete]
func (c *DetailController) Delete() {
	idStr := c.Ctx.Input.Param(":id")
	id, _ := strconv.Atoi(idStr)
	m := map[string]interface{}{}
	if err := models.DeleteDetail(int64(id)); err == nil {
		m["code"] = "20000"
	} else {
		m["code"] = "80000"
		m["message"] = err.Error()
	}
	c.Data["json"] = m
	c.ServeJSON()
}
